package top.whysu.rongcloud.global;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;
import top.whysu.rongcloud.entity.BaseEntity;

import java.util.Date;
import java.util.Properties;

/**
 * @version: 1.00.00
 * @description: SQL拦截器，给各实体对象在增加、修改时，自动添加基本属性信息。
 * @copyright:
 * @company:
 * @author:
 * @date:
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class BaseFieldInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType commandType = ms.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        Date currentTime = new Date();
        if (parameter instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) parameter;
            if (commandType.equals(SqlCommandType.INSERT)) {
                entity.setCreateTime(currentTime);
                entity.setUpdateTime(currentTime);
            } else if (commandType.equals(SqlCommandType.UPDATE)) {
                entity.setUpdateTime(currentTime);
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
